#! /bin/sh

/bin/echo "Mounting special file systems..."
/bin/mount /dev
/bin/mount /proc
/bin/mount /sys
/bin/mkdir /dev/pts
/bin/mount /dev/pts
/bin/mkdir /dev/shm
/bin/mount /dev/shm
/bin/mount -t configfs none /sys/kernel/config
/bin/mount -t debugfs nodev /sys/kernel/debug
/bin/mount -t cgroup -o all cgroup /sys/fs/cgroup

/sbin/bootlogd -c

/bin/ln -sf bash /bin/sh

if ! /bin/grep esos_iso /proc/cmdline > /dev/null 2>&1; then
    /bin/echo "Performing initial configuration sync..."
    /bin/touch /etc/esos-release
    /usr/local/sbin/usb_sync.sh --initial
fi

if [ -x /etc/rc.d/rc.udev ]; then
    /etc/rc.d/rc.udev
fi

/bin/grep -v rootfs /proc/mounts > /etc/mtab
/bin/touch /var/log/wtmp
/bin/touch /var/log/lastlog

if [ ! -L "/etc/localtime" ]; then
    /bin/ln -s /usr/share/zoneinfo/posix/Factory /etc/localtime
fi

/bin/echo "Starting kernel log daemon (klogd)..."
/usr/sbin/klogd -c1

/bin/echo "Configuring kernel parameters..."
/sbin/sysctl -p /etc/sysctl.conf

/bin/echo "Setting the x86 energy MSR policy for maximum performance..."
/usr/bin/x86_energy_perf_policy performance

if [ -f "/var/lib/esos/random-seed" ]; then
    /bin/echo "Initializing random number generator..."
    /bin/cat /var/lib/esos/random-seed > /dev/urandom
    /bin/rm -f /var/lib/esos/random-seed
fi

/bin/echo "Setting system time from hardware clock..."
/sbin/hwclock --hctosys --utc

/bin/echo "Updating module dependencies..."
/sbin/depmod -a

/bin/echo "Updating run-time linker cache..."
/sbin/ldconfig

fs_node=$(/sbin/findfs LABEL=esos_logs)
base_blk_dev="$(/bin/echo ${fs_node} | \
    /usr/bin/sed -e '/\/dev\/sd/s/4//; /\/dev\/nvme/s/p4//')"
if [ -n "${fs_node}" ]; then
    free_end=$(/usr/sbin/parted -m -s ${base_blk_dev} unit s print free | \
        egrep ':free;$' | tail -n+2 | cut -d: -f3)
    if [ -n "${free_end}" ]; then
        echo "Growing the esos_logs file system..."
        orig_start=`/usr/sbin/parted -m -s ${base_blk_dev} unit s print | \
            egrep '^4:' | cut -d: -f2`
        /usr/sbin/parted -m -s ${base_blk_dev} rm 4
        /usr/sbin/parted -m -s ${base_blk_dev} mkpart primary \
            ${orig_start} ${free_end}
        /usr/sbin/udevadm settle --timeout=30
        /sbin/blockdev --rereadpt ${base_blk_dev}
        /bin/sleep 1
        /usr/sbin/e2fsck -pf ${fs_node}
        /usr/sbin/resize2fs -p ${fs_node}
    fi
fi
